import axios from 'axios';
import * as XLSX from 'xlsx';
import UserService from './UserService.js';
import { ElMessage } from 'element-plus';
import router from '../router';

// 创建axios实例
const api = axios.create({
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
  validateStatus: status => status >= 200 && status < 300
});

// 请求拦截器，自动加token
api.interceptors.request.use(config => {
  const token = localStorage.getItem('token') || (UserService.getCurrentUser && UserService.getCurrentUser().token) || '';
  if (token) {
    config.headers.token = token;
  }
  return config;
});

// 响应拦截器
api.interceptors.response.use(
  (response) => {

    return response
  },
  (error) => {
    //如果响应的状态码为401, 则路由到登录页面
    console.log('响应错误:', error);
    if (error.response.status === 401) {
      ElMessage.error('登录失效, 请重新登录')
      router.push('/login')
    } else {
      ElMessage.success('接口访问异常')
    }
    return Promise.reject(error)
  }
);

class NewsService {
  // 获取新闻列表（分页）
  async getNewsListWithPage(params = {}) {
    try {
      // 添加当前用户ID参数
      const queryParams = { ...params };
      console.log(UserService.getCurrentUserId());
      queryParams.currentUserId = UserService.getCurrentUserId();

      console.log('NewsService - 发送分页请求参数:', queryParams);

      const response = await api.get('/api/news/list-page', { params: queryParams });
      console.log('NewsService - 获取分页新闻列表响应:', response.data);
      return response.data;
    } catch (error) {
      console.error('获取分页新闻列表失败:', error);
      throw error;
    }
  }

  // 搜索新闻
  async searchNews(params) {
    try {
      // 添加当前用户ID参数
      const queryParams = { ...params };
      queryParams.currentUserId = UserService.getCurrentUserId();

      const response = await api.get('/api/news/search', { params: queryParams });
      return response.data;
    } catch (error) {
      console.error('搜索新闻失败:', error);
      throw error;
    }
  }

  // 获取新闻详情
  async getNewsDetail(newsId) {
    try {
      const response = await api.get('/api/news/detail', {
        params: { newsId }
      });
      return response.data;
    } catch (error) {
      console.error('获取新闻详情失败:', error);
      throw error;
    }
  }

  // 新增新闻
  async addNews(news) {
    try {
      // 添加当前用户ID参数
      const currentUserId = UserService.getCurrentUserId();
      console.log('NewsService - 新增新闻，当前用户ID:', currentUserId);

      const response = await api.post('/api/news/add', news, {
        params: { currentUserId }
      });
      return response.data;
    } catch (error) {
      console.error('新增新闻失败:', error);
      throw error;
    }
  }

  // 更新新闻
  async updateNews(news) {

    const isAdmin = UserService.isAdmin();
    const response = await api.put(`/api/news/update/${isAdmin}`, news);
    return response.data;
  }

  // 删除新闻
  async deleteNews(newsId) {
    try {
      const response = await api.delete('/api/news/delete', {
        params: { newsId }
      });
      return response.data;
    } catch (error) {
      console.error('删除新闻失败:', error);
      throw error;
    }
  }

  // 审核新闻
  async reviewNews(newsId, status) {
    try {
      const response = await api.post('/api/news/review', null, {
        params: { newsId, status }
      });
      console.log('NewsService - 审核新闻响应:', response.data);
      return response.data;
    } catch (error) {
      console.error('审核新闻失败:', error);
      throw error;
    }
  }

  // 批量删除新闻 - 暂时使用循环删除单个新闻
  async batchDeleteNews(newsIds) {
    try {
      const results = [];
      for (const newsId of newsIds) {
        const response = await this.deleteNews(newsId);
        results.push(response);
      }

      // 检查是否所有删除都成功
      const successCount = results.filter(r => r.code === 200).length;
      if (successCount === newsIds.length) {
        return { code: 200, message: `成功删除 ${successCount} 条新闻` };
      } else {
        return { code: 500, message: `部分删除失败，成功删除 ${successCount} 条新闻` };
      }
    } catch (error) {
      console.error('批量删除新闻失败:', error);
      throw error;
    }
  }

  // 导出Excel - 使用xlsx库
  async exportExcel(newsList, params = {}) {
    try {
      // 准备导出数据
      const exportData = newsList.map(news => ({
        '新闻ID': news.newsId,
        '新闻标题': news.newsTitle,
        '作者': news.author,
        '新闻简介': news.newsSummary,
        '图片路径': news.newsImagePath || '无图片',
        '创建人ID': news.creatPersonId,
        '审核状态': this.getReviewStatusText(news.newsStatus),
        '新闻内容': news.newsContent || ''
      }));

      // 创建工作簿
      const workbook = XLSX.utils.book_new();

      // 创建工作表
      const worksheet = XLSX.utils.json_to_sheet(exportData);

      // 设置列宽
      const colWidths = [
        { wch: 10 }, // 新闻ID
        { wch: 30 }, // 新闻标题
        { wch: 15 }, // 作者
        { wch: 40 }, // 新闻简介
        { wch: 20 }, // 图片路径
        { wch: 12 }, // 创建人ID
        { wch: 12 }, // 审核状态
        { wch: 50 }  // 新闻内容
      ];
      worksheet['!cols'] = colWidths;

      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(workbook, worksheet, '新闻列表');

      // 生成文件名
      const fileName = `新闻列表_${new Date().toISOString().split('T')[0]}.xlsx`;

      // 导出文件
      XLSX.writeFile(workbook, fileName);

      return { success: true, message: '导出成功' };
    } catch (error) {
      console.error('导出Excel失败:', error);
      throw error;
    }
  }

  // 获取审核状态文本
  getReviewStatusText(status) {
    switch (status) {
      case 0:
        return '未审核';
      case 1:
        return '已通过';
      case 2:
        return '已拒绝';
      default:
        return '未知';
    }
  }
}

export default new NewsService(); 